#include <QDebug>
#include <QSqlError>
#include <QSqlQuery>
#include <QInputDialog>
#include <QSqlRecord>
#include <QModelIndex>
#include <QMessageBox>
#include <QDir>
#include "persistmain.h"
#include "rcqtreeview.h"
#include "ui_persistmain.h"
#include "newsample.h"
#include "pressurechart.h"

PersistMain::PersistMain(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::PersistMain)
{
    ui->setupUi(this);
    showMaximized();

#ifdef Q_WS_MAEMO_5
    setAttribute(Qt::WA_Maemo5StackedWindow,true);
    setAttribute(Qt::WA_Maemo5AutoOrientation,true);
#endif

    QString dbname = QDir::toNativeSeparators(QDir::homePath()) + QDir::separator() + "underpress.db";
    setupDatabase(dbname);
    // right click signal
    connect(ui->treeItems, SIGNAL(send_rightButtonClicked(const QPoint&)),
            this, SLOT(rightButtonClicked(const QPoint&)));
}

void PersistMain::setupDatabase(QString name)
{
    RCQTreeView *view = ui->treeItems;
    view->setRootIsDecorated(false);
    view->setAlternatingRowColors(true);

    // create a new SQLite database connector
    db = QSqlDatabase::addDatabase("QSQLITE");
    // database file
    db.setDatabaseName(name);
    if(db.open())
    {
        QSqlQuery query(db);
        // Looking for your database.
        // If it could not be found, create a new one.
        if (db.tables().indexOf("samples") == -1)
        {
            bool a,b,c;
            a = query.exec("CREATE TABLE samples (date DATE, time TIME, systolic INTEGER, "
                       "diastolic INTEGER, frequency INTEGER, note VARCHAR(512))");
            b = query.exec("CREATE TABLE config (key VARCHAR(30), Value VARCHAR(256))");
            c = query.exec("INSERT INTO config (key,value) VALUES ('version','1.0')");

            if (!(a&&b&&c))
            {
                // error open the database file
                QMessageBox::critical(this,QString(tr("Error!")),db.lastError().text());
                qApp->exit(1);
            }
        }
    }
    else
    {
        // error open the database file
        QMessageBox::critical(this,QString(tr("Error!")),tr("Could not open database ")+name);
        qApp->exit(1);
    }


    // Associating the database to the model
    dbModel = new QSqlTableModel(this,db);
    dbModel->setTable("samples");
    // Setting the edit policy
    dbModel->setEditStrategy(QSqlTableModel::OnFieldChange);
    // Load database contents 
    dbModel->select();
    // Associating the model to the view
    view->setModel(dbModel);

}

void PersistMain::on_actionAdd_triggered()
{
    NewSample dlg(this);
    dlg.setTime(QTime::currentTime());
    dlg.setDate(QDate::currentDate());
    if(dlg.exec() == QDialog::Accepted)
    {
        QSqlRecord rec = dbModel->record();
        rec.setValue("date",dlg.getDate());
        rec.setValue("time",dlg.getTime());
        rec.setValue("systolic",dlg.getSystolic());
        rec.setValue("diastolic",dlg.getDiastolic());
        rec.setValue("frequency",dlg.getFrequency());
        rec.setValue("note",dlg.getNote());

        dbModel->insertRecord(-1,rec);
    }
}

void PersistMain::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void PersistMain::rightButtonClicked(const QPoint &pos)
{
    QMenu *menu = new QMenu();
    menu->addAction(ui->actionAdd);
    menu->addAction(ui->actionEdit);
    menu->addAction(ui->actionDelete);
    menu->addAction(ui->actionChart);
    menu->exec(pos);
}

void PersistMain::on_actionEdit_triggered()
{
    QModelIndex sample = ui->treeItems->currentIndex();
    if( sample.row() >= 0 )
    {
        QSqlRecord rec = dbModel->record(sample.row());
        NewSample dlg(this);
        dlg.setDate(rec.value("date").toDate());
        dlg.setTime(rec.value("time").toTime());
        dlg.setSystolic(rec.value("systolic").toInt());
        dlg.setDiastolic(rec.value("diastolic").toInt());
        dlg.setFrequency(rec.value("frequency").toInt());
        dlg.setNote(rec.value("note").toString());

        if(dlg.exec() == QDialog::Accepted)
        {
            QSqlRecord newrec = dbModel->record();
            newrec.setValue("date",dlg.getDate());
            newrec.setValue("time",dlg.getTime());
            newrec.setValue("systolic",dlg.getSystolic());
            newrec.setValue("diastolic",dlg.getDiastolic());
            newrec.setValue("frequency",dlg.getFrequency());
            newrec.setValue("note",dlg.getNote());

            dbModel->setRecord(sample.row(),newrec);
        }
    }
}

void PersistMain::on_actionDelete_triggered()
{
    QModelIndex sample = ui->treeItems->currentIndex();
    if( sample.row() >= 0 )
    {
        QMessageBox::StandardButton dlg;
        dlg = QMessageBox::question(this, tr("Remove sample"),
                                    QString(tr("Remove sample ?")),
                                    QMessageBox::Yes | QMessageBox::No);

        if(dlg == QMessageBox::Yes)
        {
            dbModel->removeRow(sample.row());
        }
    }
}

PersistMain::~PersistMain()
{
    delete ui;
}

void PersistMain::on_actionChart_triggered()
{
    PressureChart dlg(this);
    dlg.setDb(dbModel);
    if(dlg.exec() == QDialog::Accepted)
    {
    }
}
